package com.banyuan.servlet.user;

import com.banyuan.domain.User;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/log")
public class LogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        // 通过前端设置的name来获取用户具体输入的值
        String password = req.getParameter("password");
        User user = new User(name,password);
        boolean flag = isTrue(user);

        if (flag) {
            // 如果flag返回的是true，那就是用户名和密码都输对了，存一个session值---就存当前的user对象
            HttpSession session = req.getSession();
            session.setAttribute("user",user);

            // 通过请求内部转发，将这个user对象发送到前端页面去，并且跳转到success.jsp----因为我需要写一个退出的链接,一定要加forward,否则无意义
            req.setAttribute("user",user);
            req.getRequestDispatcher("/user/success.jsp").forward(req,resp);

        } else {
            // 传送给前端一句话，让前端去展示给用户看
            req.setAttribute("msg","你还没有登陆，请登陆");
            req.getRequestDispatcher("/user/log.jsp").forward(req,resp);

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public boolean isTrue(User user) throws IOException {
        //传入一个User对象，去用户在前端输入的账号和密码去比对
        List<String> stringList = FileUtils.readLines(new File("/Users/edy/Desktop/file/2.txt"),"UTF-8");
        for (String s : stringList) {
            String[] split = s.split(",");
            if (split[0].equals(user.getName()) && split[1].equals(user.getPassword())) {
                return true;
            }
        }
        return false;
    }
}
